<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../Ajax/Day03/04.code/lib/bootstrap.css">
    <script src="./jquery.js"></script>
</head>

<body>
    <input type="file" id="file1">
    <button id='btn'>上传</button>
    <div class="progress" style="width: 500px; margin: 15px 10px;">
        <div class="progress-bar progress-bar-striped active" style="width: 0%" id="xianjian">
            0%
        </div>
    </div>
    <br>
    <img src="" alt="" id="img" width="800">
    <script>
        var btn = document.querySelector('#btn')
        btn.addEventListener('click', function () {
            var files = document.querySelector('#file1').files
            if (files.length <= 0) {
                return alert('请选择上传的文件')
            }
            // 将用户选择的文件上传到FormDate
            var fd = new FormData();
            fd.append('avater', files[0])
            var xhr = new XMLHttpRequest();
            // 监听xhr.upload的onprogress事件
            xhr.upload.onprogress = function (e) {
                if (e.lengthComputable) {
                    // 上传进度百分比显示
                    var xyy = Math.ceil((e.loaded / e.total) * 100)
                    console.log(xyy);
                    $('#xianjian').attr('style', 'width:' + xyy + '%').html(xyy + '%')
                }
            }
            xhr.upload.onload = function () {
                $('#xianjian').removeClass().addClass('progress-bar progress-bar-success')
            }
            // 调用open函数
            xhr.open('POST', 'http://www.liulongbin.top:3006/api/upload/avatar')
            // 调用send函数
            xhr.send(fd)
            // 监听onreadystatechange

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var data = JSON.parse(xhr.responseText)
                    if (data.status === 200) {
                        // 上传成功
                        document.querySelector('#img').src = 'http://www.liulongbin.top:3006' + data.url
                    } else {
                        // 上传失败
                        console.log('图片上传失败！' + data.message)
                    }
                }
            }
        })
    </script>
</body>

</html>